package yao.config;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;

import yao.config.exception.ConfigException;
import yao.config.exception.ConfigPathException;


/**
 * 配置文件路径
 * 
 * @author YaoMing
 */
public final class ConfigPath {

	private String path;

	private File file;

	/**
	 * 构造
	 * 
	 * @param configpath
	 * @throws ConfigException
	 * @throws ConfigPathException
	 */
	ConfigPath(String path) throws ConfigPathException {
		if (null == path || (path = path.trim()).equals("")) {
			throw new ConfigPathException("Illegal config path: \"" + path + "\"");
		}
		this.path = path;

		int pot = path.indexOf("classpath:");
		if (pot != -1) {
			String _path = path.replaceFirst("classpath:", "").trim();
			if (_path.equals("")) {
				throw new ConfigPathException("Illegal config path: \"" + path + "\"");
			}
			URL _url = getClass().getClassLoader().getResource(_path);
			if (_url == null) {
				throw new ConfigPathException("Illegal class path \"" + path + "\"");
			}
			String filename = _url.getPath();
			try {
				filename = URLDecoder.decode(_url.getPath(), "utf8");
			} catch (UnsupportedEncodingException e) {
			}
			file = new File(filename);
		} else {
			file = new File(path);
		}

		if (!file.exists()) {
			throw new ConfigPathException("Not exists \"" + path + "\"");
		}
	}

	public String getPath() {
		return path;
	}

	public File getFile() {
		return file;
	}

	public String toString() {
		return path;
	}
}
